package org.test.once.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.test.once.model.Role;
import org.test.once.model.User;
import org.test.once.manager.RoleManager;
import org.test.once.manager.UserManager;

public class RoleServlet extends HttpServlet{
	
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("GB2312");

		RoleManager roleManager = new RoleManager();
		String oder=req.getParameter("oder");
		String order = req.getParameter("order");

		if ("addRole".equals(oder)) {
			String name = req.getParameter("name");
			Role role = new Role();
			role.setName(name);
			roleManager.addRole(role);
			req.getRequestDispatcher("role/pub_add_success.jsp").forward(req,resp);
		} 
		if("modify".equals(order)) {
			String roleId = req.getParameter("roleId");
			String roleName = req.getParameter("rolename");
			Role role = new Role();
			role.setId(Integer.parseInt(roleId));
			role.setName(roleName);
			roleManager.updateRole(role);
			req.getRequestDispatcher("role/pub_update_success.jsp").forward(req,resp);
		}
		
		if("update".equals(req.getParameter("order"))){
			String roleid = req.getParameter("roleid");
			int id = Integer.parseInt(roleid);
			Role role=roleManager.findRoleById(id);
			req.setAttribute("role",role);
			req.getRequestDispatcher("role/update_info.jsp").forward(req, resp);
		}
		
		if("delRole".equals(oder)){
			String roleid=req.getParameter("roleid");
			int id=Integer.parseInt(roleid);
			roleManager.delRole(id);
			req.getRequestDispatcher("role/pub_del_success.jsp").forward(req,resp);
		}
		
		if("search".equals(oder)){
			List<Role> roles = roleManager.searchRoles();
			req.setAttribute("roles", roles);
			req.getRequestDispatcher("role/role_list.jsp").forward(req, resp);
		}
		if("searchlist".equals(oder)){
			List<Role> roles = roleManager.searchRoles();
			int id = Integer.parseInt(req.getParameter("id"));
			
			//System.out.println(id);
			UserManager um = new UserManager();
			User user = um.findUserById(id);
			req.setAttribute("roleuser", user);
			req.setAttribute("roles", roles);
			req.getRequestDispatcher("user/role_list.jsp").forward(req, resp);
		}
	
	  }
	
}

